package common

import (
	"errors"
	"fmt"
	"time"

	"gorm.io/gorm"
)

type ExpireTable struct {
	TableName    string
	CompareField string
	Interval     string
}

var expireTables []ExpireTable

func init() {
	expireTables = append(expireTables, ExpireTable{
		TableName:    "sys_operation_records",
		CompareField: "created_at",
		Interval:     "2160h",
	})

	expireTables = append(expireTables, ExpireTable{
		TableName:    "jwt_blacklists",
		CompareField: "created_at",
		Interval:     "168h",
	})
}
func ExpireRecord(db *gorm.DB) error {
	if db == nil {
		return errors.New("db Cannot be empty")
	}

	for _, detail := range expireTables {
		duration, err := time.ParseDuration(detail.Interval)
		if err != nil {
			return err
		}
		if duration < 0 {
			return errors.New("parse duration < 0")
		}
		err = db.Debug().Exec(fmt.Sprintf("DELETE FROM %s WHERE %s < ?", detail.TableName, detail.CompareField), time.Now().Add(-duration)).Error
		if err != nil {
			return err
		}
	}
	return nil
}
